package fr.cavalier.sort;

import java.util.Arrays;

public class SimplesSort {

	
	public static void insertionSort(int[] array){
		long startTime = System.currentTimeMillis();
		int j = 0;
		int buffer;
		int nbStep = 0;
		for(int i= 1; i<array.length; i++){
			buffer=array[i];
			j= i-1;
			while (j>=0 && buffer< array[j] ){
				array[j+1]=array[j];
				array[j]=buffer;
				j-=1;
				nbStep++;
			}
		}
		long endTime = System.currentTimeMillis();
//		printArray(array);
		System.out.println("InsertionSort : time for "+array.length+" element ="+(endTime-startTime)+"ms for "+nbStep+" steps.");
	}
	
	public static void selectionSort(int[] array){
		long startTime = System.currentTimeMillis();
		int buffer = 0;
		int min = 0;
		int nbStep = 0;
		for(int i=0;i<array.length;i++){
			nbStep+=array.length-i;
			min =getMinimalIndice(Arrays.copyOfRange(array, i, array.length));
			buffer=array[i];
			array[i]=array[min+i];
			array[min+i]=buffer;
		}
		long endTime = System.currentTimeMillis();
//		printArray(array);
		System.out.println("SelectionSort : time for "+array.length+" element ="+(endTime-startTime)+"ms for "+nbStep+" steps.");
	}
	
	public static void bubbleSort(int[] array){
		int buffer;
		long startTime = System.currentTimeMillis();
		boolean hasSwitched;
		int nbStep = 0;
		do {
			hasSwitched = false;
			for(int i=0; i<array.length-1; i++){
				if(array[i]>array[i+1]){
					hasSwitched = true;
					nbStep++;
					buffer = array[i];
					array[i]=array[i+1];
					array[i+1]=buffer;
				}
			}
		} while(hasSwitched == true);
		long endTime = System.currentTimeMillis();
		System.out.println("BubbleSort : time for "+array.length+" element ="+(endTime-startTime)+"ms for "+nbStep+" steps.");

	}
	
	public static void bubbleSort2(int[] array){
		int buffer;
		long startTime = System.currentTimeMillis();
		boolean hasSwitched;
		int nbStep = 0;
		do {
			hasSwitched = false;
			for(int i=1; i<array.length; i++){
				if(array[i-1]>array[i]){
					hasSwitched = true;
					nbStep++;
					buffer = array[i-1];
					array[i-1]=array[i];
					array[i]=buffer;
				}
			}
		} while(hasSwitched == true);
		long endTime = System.currentTimeMillis();
		System.out.println("BubbleSort : time for "+array.length+" element ="+(endTime-startTime)+"ms for "+nbStep+" steps.");
	}
	
	public static int getMinimalIndice(int[] array){
		int min =0;
		for(int i = 1; i<array.length; i++){
			if(array[i]<array[min]){
				min = i;
			}
		}
		return min;
	}
	
	public static void printArray(int[] array){
		String stout = "=> (";
		for(int i : array){
			stout+=i+" | ";
		}
		stout=stout.substring(0, stout.length()-2);
		stout+=")";
		System.out.println(stout);
	}
}
